﻿using Client.Framework.Message;
using Client.Framework.Util;
using Google.Protobuf;
using SuperSocket.ProtoBase;
using System;


namespace Client.Framework.Socket
{
    /// <summary>
    /// Author: Leil
    /// Description: 自定义消息协议类
    /// CreateTime: 2020/5/12 9:21:09
    /// </summary>
    class ProtobufReceiveFilter : IReceiveFilter<ProtobufPackageInfo>
    {
        public IReceiveFilter<ProtobufPackageInfo> NextReceiveFilter { get; }

        public FilterState State { get; }

        private byte[] swapBuffer;

        private int sumLength = 0;

        private int alreadySwap = 0;

        public ProtobufPackageInfo Filter(BufferList data, out int rest)
        {
            rest = 0;
            ArraySegment<byte> buffer = data.Last;
            int offset = buffer.Offset;
            int length = buffer.Count;
            byte[] bytes = buffer.Array;
            if (length < 16) { return default; }
            if (sumLength == 0)
            {
                int bodyLength = BufferUtil.GetInt(bytes, offset + 12);
                sumLength = 16 + bodyLength;
                swapBuffer = new byte[sumLength];
            }
            if (alreadySwap + length <= sumLength)
            {
                Array.Copy(bytes, offset, swapBuffer, alreadySwap, length);
                alreadySwap += length;
            } else
            {
                int copyLength = sumLength - alreadySwap;
                Array.Copy(bytes, offset, swapBuffer, alreadySwap, copyLength);
                rest = length - copyLength;
            }
            if (data.Total >= sumLength)
            {
                ResponseBaseMessage message = MessageDecoder.Decode(swapBuffer, 0);
                if (message == null)
                {
                    return default;
                }
                ProtobufPackageInfo receiveInfo = new ProtobufPackageInfo(message);
                //Reset();
                return receiveInfo;
            }
            return default;
        }

        public void Reset()
        {
            swapBuffer = null;
            sumLength = 0;
            alreadySwap = 0;
        }
    }
}
